// components/approve_v2/approve_v2.js

const req = require('../../utils/request');
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tableid: {
      type: String,
      observer(val){
        this.getUser();
      }
    },
    rowid:{
      type: String
    },
    //业务数据是否已审批
    is_checked: {type: Boolean},
    isNew: {
      type: Boolean
    },
  },

  /**
   * 监听数据
   */
  observers:{
    async 'tableid, rowid, isNew'(tableid,rowid,isNew){
      // await this.getApprovalList();
      if (tableid && rowid){
        /*if (isNew) {

          let obj = {};

          if (this.data.approveProcess){
            //231030 yan 修改
            // obj.sbmBtnStatus = 3;
            // if (this.data.approveProcess.is_choose)obj.sbmFlag = true;
            obj.sbmBtnStatus = 1;
            if (this.data.approveProcess.is_choose){
              obj.sbmFlag = true;
              obj.sbmBtnStatus = 3;
            }
          }else {
            obj.sbmBtnStatus = 0;
          }
          this.setData(obj);

          return
        }*/
        console.log(rowid);
        this.getApprovalProcess();
      }
    }
  },
  //
  /**
   * 组件的初始数据
   */
  data: {
    showMore: false,  //显示更多操作标识
    showConfirm: false, //显示确认审批弹出层标识
    selectFlag: false,  //用户列表弹出层标识
    showComment: false, //添加评论弹出层标识
    sbmFlag: false, //自由审批选择界面
    allowSubmit: false, //允许提交审批

    curSelectUserType: null,  //当前选择用户用途（transfer转交，nextList、aprList、copyList

    commentIptVal: null,   // 评论内容
    approveIptVal: null,   // 审批内容

    aprList: [],  //自由审批审批人
    copyList: [], //自由审批抄送人
    nextList: [], //下一审批人已选列表

    aprUserFlag: false, //当前是否可操作审批标识

    moreBtns: [
      // {name: '撤销',icon: 'revoke'},
      // {name: '评论',icon: 'comment-o'},
      // {name: '转交',icon: 'share-o'},

    ],

    logs: [], //审批记录
    approveProcess: null, //审批配置
    approveList: [],  //审批配置记录
    operateConfig: {},  //当前可操作用户审批配置

    confirmState: null, //提交审批状态（拒绝，同意）


    showSignature: false, //显示签名组件标识
    watermark: [{
      content: '$time$',
      font: '24px serif',
      position: {
        bottom: 15,
        left: 15
      }
    },
      {
        content: '$location$',
        font: '22px serif',
        position: {
          bottom: 42,
          left: 15
        }
      },],    //签名水印

    system_id: wx.getStorageSync('system_id') || 800,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /*-----------------------交互 ---------------------*/
  //  显示更多操作
    bindShowMore(){
      this.setData({showMore: true})
    },
    //关闭显示更多操作
    bindClose(e){
      let {flag} = e.currentTarget.dataset;
      this.setData({[flag]: false})
    },
    //阻止冒泡
    stopBubbling(){},

    // 预览图片
    previewImg(e){
      let { url, } = e.currentTarget.dataset;
      let {  system_id,baseURL } = this.data;
      let src = `${baseURL}/files/${system_id}/${url}`

      wx.previewImage({
        current: src,
        urls: [src]
      })
    },
    //  切换隐藏显示下级数据
    bindToggleChild(e){
      let {index} = e.currentTarget.dataset,
        {logs} = this.data,
        data = logs[index];
      if (!data.child ?. length ) return;
      let isOpen = !data.isOpen;
      this.setData({[`logs[${index}].isOpen`]: isOpen})
    },

    //审批
    bindShowConfirm(e){
      let {state} = e.currentTarget.dataset;
      this.setData({
        confirmState: state,
        showConfirm:true
      })
    },
    //确认提交审批
    bindConfirm(){
      let {approveIptVal,confirmState,nextList,operateConfig,need_upload_sign_pic} = this.data;
      if (operateConfig?.need_upload_sign_pic) {
        this.setData({showSignature:true});
        return
      }

      let nextid = [],
        nextname = [];
      nextList?.forEach(item => {
        nextid.push(item.id);
        nextname.push(item.name)
      });
      wx.showLoading({mask: true})
      this.submitApproval(confirmState,approveIptVal,nextid,nextname).then(() => {
        wx.hideLoading();
        this.data.confirmState = null;
        this.setData({showConfirm:false})
      })
    },

    //签名完操作
    onSign({detail}){
      this.setData({showSignature:  false});
      wx.showLoading({mask: true});
      wx.$uploadReq(detail).then(res =>{
        if (res.response.errcode != 0) {
          wx.$toast(res.errmsg);
          return
        }
        let data = res.data.row[0];
        let {approveIptVal,confirmState,nextList} = this.data;

        let nextid = [],
          nextname = []
        nextList?.forEach(item => {
          nextid.push(item.id);
          nextname.push(item.name)
        });

        this.submitApproval(confirmState,approveIptVal,nextid,nextname,data?.filename).then(() => {
          wx.hideLoading();
          this.data.confirmState = null;
          this.setData({showConfirm:false})
        });
      })
    },
    onSignCancel(){
      this.setData({showSignature:  false});
    },

    //点击更多中的按钮操作
    bindBtnOperate(e){
      let {name} = e.currentTarget.dataset;
      if (name === '转交'){
        this.setData({selectFlag: true,curSelectUserType: 'transfer'})
      }
      if (name === '撤销'){
        this.undoApprove();
      }
      if (name === '评论'){
        this.setData({showComment: true})
      }
    //
    },

    //选中用户
    bindSelectUser(e){
      let detail = e.detail,
        type = this.data.curSelectUserType,
        list = this.data[type],
        obj = {
          selectFlag:false
        };
      if ((type === 'copyList' && !list.some(item =>item.id === detail.id)) || (['aprList','nextList'].includes(type))  ){
        list.push(detail);
        obj[type] = list;
      }
      console.log(obj);
      this.setData(obj);
      if (type === 'transfer') this.transferApprove(detail)
    },
    //删除选中用户
    bindDelUser(e){
      let dataset = e.currentTarget.dataset,
        type = dataset.type,
        index = dataset.index,
        list = this.data[type];
      list.splice(index,1);
      this.setData({
        [type]: list
      })
    },

    //确定提交评论
    bindComment(){
      let {commentIptVal} = this.data;
      if (!commentIptVal) {
        wx.$toast('请输入评论内容');
        return
      }
      wx.showModal({
        title: '评论',
        content: '确定发送评论？',
        success: (res) =>{
          if (res.confirm){
            wx.showLoading({mask: true});
            this.sendComment(commentIptVal).then(errcode =>{
              if (errcode != 0) return;
              this.setData({showComment: false});
              wx.hideLoading()
            // 刷新记录
              this.getApprovalProcess();
            })
          }
        }
      })
    },

    //添加下一审批人
    bindAddApprover(e){
      let {type} = e.currentTarget.dataset;
      this.setData({selectFlag: true,curSelectUserType: type})
    },

    //提交审批
    async bindSubmitApprove(){
      await this.getApprovalList();
      let {approveList,approveProcess} = this.data,
        {is_choose} = approveProcess;
      if (is_choose){
        this.setData({
          sbmBtnStatus: 3,
          sbmFlag: true
        });
      } else {
        wx.showModal({
          title: '提交审批',
          content: '确定提交审批？',
          success: (res) =>{
            if (res.confirm){
              wx.showLoading({mask: true})
              this.submitApproval('提交').then(() =>{
                this.setData({allowSubmit:false});
                this.triggerEvent('apr_state', false);
               wx.hideLoading()
              })
            }
          }
        })
      }
    },

    //提交自由审批
    bindConfirmFreeApproval(){
      wx.showModal({
        title: '提交',
        content: '确定提交自由审批？',
        success: (res)=>{
          if (res.confirm){
            wx.showLoading({mask: true});
            this.submitFreeApproval().then(() =>{
              this.setData({sbmFlag: false})
              wx.hideLoading();
              this.getApprovalProcess();
              this.triggerEvent('approve');
            })
          }
        }
      })
    },

    /*---------------------- 审批相关 -----------------------*/

    //获取审批列表
    getApprovalList(){
      let {rowid,tableid,approveList} = this.data,
        post = {
          limit: 10000,
          oby: "process_id desc",
          page: 1,
          SearchWhere: [
            {
              "CompareWith": "table_id",
              "Operator": "=",
              "CompareValue": tableid,
              "or": 0
            },
            {
              "CompareWith": "status",
              "Operator": "=",
              "CompareValue": true,
              "or": 0
            }
          ]
        };

      return new Promise(resolve => {
        if (approveList?.length){
          resolve();
          return
        }
        wx.$post(3,'Approval_process/query_approval_process',post).then(res=>{
          if (res.errcode != 0)return;
          let list = [],
            data = res.data.row || [];
          this.setData({approveListAll: data})
          wx.$each(data,async (i,item) =>{
            if(['null',null,'undefined',undefined,''].includes(item.combination_query_json)){
              list.push(item);
              return
            }
            if (await this.approveFilter(rowid,item.combination_query_json)){
              list.push(item);
            }
          });
          if (list[0]){
            let info = list[0],
              isChoose = info.is_choose,
              process_id = info.process_id,
              process_name = info.process_name,
              obj = {};
            obj.approveProcess = info;//第一条审批数据
            obj.approveList = list;
            this.setData(obj);

          }else {
            wx.$toast('没有可提交的审批流程，请设置审批流程！');
          }
          resolve();
        });
      })
    },

    //判断审批
    async approveFilter(rowid,query){
      let tableid = this.data.tableid,
        ARR = this.eachFilter(tableid,[JSON.parse(query)]),
        where = {
          "CompareWith": tableid + '.row_id',
          "Operator": '=',
          "CompareValue": rowid,
          "or": 0
        };
      ARR.push(where);
      let post = {
          limit: 1,
          oby: tableid + ".row_id desc",
          page: 1,
          table_id: tableid,
          SearchWhere: ARR
        },
        flag = false;
      await wx.$post(3,'DynamicQuery/query_dynamic_v1',post).then(res =>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        if (data.length === 0)return;
        flag = true;
      });
      return flag;
    },
    //级联对象筛选条件转为同级数组
    eachFilter(arr){
      let ARR = [],
        tableid = this.data.tableid;
      wx.$each(arr,(i,item) =>{
        let filters = item.filters,
          type = item.type;
        wx.$each(filters,function (ind,ite) {
          let compareWith = (ite.fieldName || ite.CompareWith);
          compareWith = compareWith.indexOf('.') >= 0 ? compareWith : (tableid + '.' + compareWith);
          let obj = {
            "CompareWith": compareWith,
            "Operator": (ite.operator || ite.Operator),
            "CompareValue": (ite.value || ite.CompareValue || '').toString(),
            "or": (type.toLocaleString() === "and" ? 0 : 1)
          };
          ARR.push(obj);
        });
        ARR = ARR.concat(this.eachFilter(item.children || []));
      });
      return ARR;
    },

    //获取审批记录
    getApprovalProcess(){
      let url =  'Approval_process/query_approval_process_log',
        {rowid,tableid} = this.data,
        data = {table_id: tableid,row_id: rowid}
      wx.$get(3,url,data,false,true).then(res =>{
        //没有数据--显示提交审批按钮
        if (!res.data.length){
          this.setData({allowSubmit:true});
          this.triggerEvent('apr_state', false);
          return
        }
        //有数据
        this.isApprovalUser();
        this.formatLogs(res.data)
      })
    },


    /**
     * 格式化审批记录
     * 1、先把审批记录按group_id和process_step_id分组
     * 没有group_id和process_step_id的单独一条数据用当前时间戳+index标识
     * abstract_值为抄送的分为一组
     * 2、抄送分组的，审批结束且不是拒绝审批的显示，否则不显示。
     * 3、（group_id为空 || group_id不为空但end_able已结束）&& 修改时间为空 && 审批已结束 && 不是评论抄送的 && 审批准固态为已拒绝
     * 的审批记录不显示
     * 即系审批拒绝之后，原本需要审批的操作或抄送不显示，但可以显示评论
     * 审批记录中包含original_approver_id代表是转交而来的数据，需要显示转交人记录
     *
     * @param data
     * @return {Array}
     */
    formatLogs(data){
      //按分组号和步骤号分组，得到数组对象
      let groups = this.groupBy(data,['group_id','process_step_id',]),
        logs = [],
        currStep = -1,
        isAprEnd = false,
        aprEndState = '';
      console.log(groups);
      //遍历数组对象
      Object.keys(groups).forEach((item,index) =>{
        let orgArr = groups[item];

        //抄送直接显示
        if (item === "抄送"){
          //审批结束之后再显示
          isAprEnd && !['已拒绝','已撤销'].includes(aprEndState) && logs.push({child: orgArr,title: "抄送",isOpen: false,message: "抄送人",avatar: "volume-o",isCopy: true})
          return
        }

        //当前分组只有一条数据时，直接添加在logs中
        if (orgArr.length === 1){
          currStep = index;
          let {original_approver_id,group_id,end_able,abstract_,modify_time,state,user_name} = orgArr[0]

          //审批已结束切当前组id为0且非评论时不显示
          // if ((!group_id || end_able) && !modify_time && isAprEnd && abstract_ !== '评论') return
          if ((!group_id || (group_id && end_able) ) && !modify_time && isAprEnd && !['评论','抄送'].includes(abstract_) && ['已拒绝','已撤销'].includes(aprEndState)) return

          if (original_approver_id) {
            let {original_approver_name,transfer_time} = orgArr[0]
            logs.push({
              abstract_: "审批人",
              modify_time: transfer_time,
              state: '已转交给' + user_name,
              user_name: original_approver_name,
            })
          }
          if (group_id){
            isAprEnd = end_able;
            modify_time && (aprEndState = state)
          }

          if (abstract_.indexOf('申请') >= 0){
            aprEndState = '申请'
          }

          logs.push(orgArr[0])
        }
        //分组中有多条数据，循环判断其中数据是否已审核，已审核的直接添加到logs中，未审核的保留在数组中
        else {
          let i = 0,
            isAllEnd = true,  //是否已全部结束
            isNoEnd = true,   //是否一个都没有结束
            endState = false; //是否已拒绝
          while (i<orgArr.length){
            let ite = orgArr[i],
              {modify_time,group_id,end_able,abstract_,process_step_name,allow_transfer,sign_type,state,original_approver_id,original_approver_name,transfer_time,user_name} = ite;
            ['已拒绝','已撤销'].includes(state) && (endState = true);
            //审批已结束切当前组id为0时不显示
            // if ((!group_id || end_able) && !modify_time && isAprEnd && abstract_ !== '评论') return
            if ((!group_id || (group_id && end_able) ) && !modify_time && isAprEnd && !['评论','抄送'].includes(abstract_) && ['已拒绝','已撤销'].includes(aprEndState)) return;

            //group_id有数时，判断end_able，true标识该审批已结束
            if (group_id) {
              isAprEnd = end_able;
              modify_time && (aprEndState = state)
            }

            if (original_approver_id) {
              logs.push({
                abstract_: "审批人",
                modify_time: transfer_time,
                state: '已转交给' + user_name,
                user_name: original_approver_name,
              })
            }

            //判断修改时间，表示已审核
            if (modify_time){
              logs.push(ite); //添加到logs数组中
              orgArr.shift();  //删除当前数据
              currStep = index; //记录当前审批分组索引
              isNoEnd = false;
            } else {
              isAllEnd = false;
              i++;
            }
          }
          //当前数组中还有未审核数据时
          if (orgArr.length){
            let {modify_time,abstract_,process_step_name,allow_transfer,sign_type} = orgArr[0],
              title = '',isOpen = false,message = '',avatar = '',isCopy = false;
            //如果当前分组审批中已拒绝则跳过
            if (endState) return
            //判断显示标题
            switch (true) {
              //部分已审核
              case !isAllEnd && !isNoEnd:
                if (!sign_type) {
                  title = `${process_step_name} ${orgArr.length}人会签`;
                  message = '审批人';
                  avatar = 'friends-o'
                }else {
                  title = `${process_step_name} 或签审批人`
                  message = '该步骤已审批'
                  avatar = 'volume-o'
                  isCopy = true;
                }
                isOpen = true;
                break;
              //全部都未审核
              case !isAllEnd && isNoEnd:
                isOpen = currStep === (index -1) && index !== 0;
                title = `${process_step_name} ${orgArr.length}人${sign_type ? '或签': '会签'}`
                message = '审批人'
                avatar = 'friends-o'
                break;
            }
            logs.push({child: orgArr,title,isOpen,message,avatar,isCopy})
          }
        }
      });
      let obj = {logs};
      if (isAprEnd && ['已拒绝','已撤销'].includes(aprEndState)|| ![ '已同意','已提交','已重新提交','申请'].includes(aprEndState)){
        obj.allowSubmit = true;
      }else if(isAprEnd)obj.allowSubmit = false;


      this.setData(obj);

      //通知父组件，当前是否审批中，能否修改业务数据（审批已结束且拒绝状态可修改
      // let allowModify = (isAprEnd && aprEndState === '已拒绝')
      // console.log(allowModify);
      // this.triggerEvent('apr_state', allowModify);

      if (['已同意','已提交','已重新提交','申请'].includes(aprEndState)){
        this.triggerEvent('apr_state', true);
      }else {
        this.triggerEvent('apr_state', false);
      }
    },

    // 审批记录分组
    groupBy(arr,key,){
      return arr.reduce((prev,curr,index)=>{
        let keys = [];
        if (typeof key === 'object'){
          key.forEach(ite =>{
            curr[ite] && keys.push(curr[ite]);
          });

        }else{
          curr[key] && keys.push(curr[key]);
        }

        //发起申请
        if (curr.abstract_.indexOf( "申请") >= 0){
          prev[new Date().getTime() + index] = [curr];
          return prev;
        }

        if(keys.length){
          (prev[keys.join('_')] = prev[keys.join('_')] || []).push(curr);
        }else if (curr.abstract_ === "抄送") {
          prev["抄送"] = [...prev["抄送"] || [],curr];
        }else{
          //程序执行过快会获取到同一个时间戳导致数据被覆盖，增加一个index区分
          prev[new Date().getTime() + index] = [curr]
        }
        return prev;
      },{})
    },

    //获取当前人员是否可操作审批
    isApprovalUser (isEnd){ //是否已结束,已结束不可操作
      let {tableid,rowid} = this.data,
        post = {
          "table_id": tableid,
          "row_id": rowid
        };
      wx.$post(3,'Approval_process/get_approval_process_operate',post).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row?.[0],
          is_operate = data?.is_operate;
        let moreBtns = [];

        data?.is_cancel && moreBtns.push({name: '撤销',icon: 'revoke'});
        data?.allow_transfer && moreBtns.push({name: '转交',icon: 'share-o'});
        moreBtns.push({name: '评论',icon: 'comment-o'})
        console.log(is_operate && !isEnd);
        this.setData({
          aprUserFlag: !!(is_operate && !isEnd),
          operateConfig: data || {},
          moreBtns
        });
      });
    },
    //
    //转交审批
    transferApprove(detail){
      wx.showModal({
        title: '转交',
        content: `确定转交该审批给${detail.name}？`,
        success: res =>{
          if (res.confirm){
            wx.showLoading({mask: true})
            //转交审核
            this.submitApproval('转交','',[detail.id],[detail.name]).then(() => wx.hideLoading())
          }
        }
      })
    },
    //撤销审批
    undoApprove(){
      wx.showModal({
        title: '撤销',
        content: `确定撤销该审批？`,
        success: res =>{
          if (res.confirm){
            wx.showLoading({mask: true})
            //转交审核
            this.submitApproval('撤销',).then(() => wx.hideLoading())
          }
        }
      })
    },

    //提交固定审批
    submitApproval(state,mark,nextids = [],nextnames = [],sign_pic) { //审批状态
      let {tableid,rowid,approveProcess,} = this.data,
        proid = approveProcess && approveProcess.process_id,
        post = {
          "table_id": tableid,
          "row_id": rowid ,
          "sh_state": state,
          "next_sh_id":"",
          "next_sh_name":"",
          "sh_mark": mark || "",
          process_id: '',
          sign_pic
        };
      let nextid = [...nextids],
        nextname = [...nextnames]

      nextid.length && (post.next_sh_id = nextid.join(','))
      nextname.length && (post.next_sh_name = nextname.join(','))

      if (state.indexOf('提交') >= 0){post.process_id = proid}
      return new Promise(resolve => {
        wx.$post(3,'Approval_process/update_approval_process_log',post).then(res=>{
          this.getApprovalProcess();
          this.triggerEvent('approve');
          resolve();
        });
      });

    },

    //提交评论
    sendComment(mark){
      let url = 'Approval_process/table_row_comment',
        {tableid,rowid} = this.data,
        post = [
          {
            "table_id": tableid,
            "table_row_id": rowid,
            "comment": mark
          }
        ];
      return wx.$post(3,url,post).then((res) =>{
        return res.errcode

      })
    },


    //提交自由审批
    submitFreeApproval(rid){
      return new Promise((resolve) => {
        let {aprList, copyList, approveProcess,tableid, rowid,process_id} = this.data,
          post = {
            "process_id": approveProcess && approveProcess.process_id || process_id,
            "table_id": tableid,
            "row_id": rid || rowid,
            "apply_mark": '',
            "apply_attachment_list": '',
            "apply_approver_list": '',
            "apply_cc_list": ''
          },
          aprArr = [],
          copyArr = [];

        if (aprList.length === 0){
          wx.$toast('请先选择审批人!');
          return
        }

        wx.$each(aprList,(i,item)=>{
          aprArr.push(item.id);
        });
        wx.$each(copyList,(i,item)=>{
          copyArr.push(item.id);
        });

        post.apply_approver_list = aprArr.join(',');
        post.apply_cc_list = copyArr.join(',');
        wx.$post(3,'Approval_process/create_approval_process_log2',post).then(res=>{
          resolve();
        });
      })
    },


    /*----------------------- 基础资料 -------------------------*/

    //获取用户列表
    getUser(){
      wx.$get(3,'BaseTable/select_user').then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        this.setData({userList: data});
      })
    },



  }
})
